<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../../static/lib/layui-v2.9.8/css/layui.css" media="all">
    <link rel="stylesheet" href="./../../static/css/public.css" media="all">
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">
        <fieldset class="table-search-fieldset">
            <legend>扫码入库</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="" lay-filter="form-filter">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">条形码识别</label>
                            <div class="layui-input-inline">
                                <input type="text" id="product-id-input"  class="layui-input"
                                       autofocus="autofocus">
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>
        <fieldset class="table-search-fieldset">
            <legend>查询条件</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="" lay-filter="form-filter">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">装备器材名字</label>
                            <div class="layui-input-inline">
                                <input type="text" name="fk_product__name" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        {% if request.session.role_id == 1 %}
                            <div class="layui-inline">
                                <label class="layui-form-label required">库房名字</label>
                                <div class="layui-input-inline">
                                    <select name="fk_department" lay-search="" lay-verify="fk_department">
                                        <option value="">选择库房名字</option>
                                        {% for item in departments %}
                                            <option value="{{ item.pk }}">{{ item.name }}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                            </div>
                        {% endif %}
                        <div class="layui-inline">

                            <button type="submit" class="layui-btn layui-btn-normal" lay-submit
                                    lay-filter="data-search-btn"><i class="layui-icon"></i> 查 询
                            </button>


                            <button type="reset" class="layui-btn layui-btn-primary"><i
                                    class="layui-icon layui-icon-refresh"></i> 重 置
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-primary layui-border-green layui-btn-xs data-count-edit"
               lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-xs layui-btn-primary layui-border-red data-count-delete"
               lay-event="delete">删除</a>
        </script>
        <script type="text/html" id="toolbarUser">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-primary layui-border-green layui-btn-sm data-add-btn"
                        lay-event="send"> 入库
                </button>
            </div>
        </script>
    </div>
</div>
<script src="../../../static/lib/layui-v2.9.8/layui.js" charset="utf-8"></script>
<script>
    layui.use(['form', 'table'], function () {
            var $ = layui.jquery,
                form = layui.form,
                table = layui.table;

            var userID = $("#login_user", parent.document).text();

            var token = "{{ csrf_token }}"
            $.ajaxSetup({
                headers: {
                    'X-CSRFTOKEN': `${token}`,
                    'AUTHORIZATION': 'Bearer ' + localStorage.token,
                }, // JWTAuthentication.authenticate()方法获取 header = request.META.get(api_settings.AUTH_HEADER_NAME),
            });


            $.ajaxSetup({
                complete: function (XMLHttpRequest, textStatus) {
                    if (XMLHttpRequest.status === 401) {  // 401 表示未授权，即 token 无效
                        layer.msg('授权已过期，需重新登陆', {icon: 2, time: 2000}, function () {
                            window.location.href = '/login';
                        })
                    }
                }
            });

            window.parent_msg = function (msg) {
                layer.msg(msg, {icon: 1})
            }

            table.render({
                elem: '#currentTableId',
                url: '/put_storage_manage_list/',
                method: 'get',
                toolbar: '#toolbarUser',
                defaultToolbar: ['filter', 'exports', 'print'],
                cols: [[
                    {type: "checkbox", width: 50},
                    {field: 'count', width: 100, title: '序号', align: 'center', sort: true, type: 'numbers'},
                    {field: 'id', width: 100, title: 'ID', align: 'center', hide: true},
                    {field: 'name', width: 200, title: '装备器材名称', align: 'center'},
                    {field: 'department_name', width: 150, title: '库房名字', align: 'center'},
                    {field: 'product_quantity', width: 360, title: '仓存数量', align: 'center'},
                    {field: 'quantity', width: 360, title: '入库数量', align: 'center'},
                    //{title: '操作', minWidth: 200, toolbar: '#currentTableBar', align: "center"}
                ]],
                limits: [10, 15, 20, 25, 50, 100],
                limit: 10,
                skin: 'grid',
                even: false,
                page: true,
                parseData: function (res) { //res 即为原始返回的数据
                    console.log(res)
                },
                before: function (res, curr, count) {
                },
                done: function (res, curr, count) {

                }

            });

            // 监听搜索操作
            form.on('submit(data-search-btn)', function (data) {
                console.log(data.field);
                var result = JSON.stringify(data.field);

                //执行搜索重载
                table.reload('currentTableId', {
                    page: {
                        curr: 1
                    }
                    , where: {
                        Params: result
                    }
                }, 'data');

                return false;
            });

            /**
             * toolbar监听事件
             */
            table.on('toolbar(currentTableFilter)', function (obj) {
                if (obj.event === 'send') {  // 监听添加操作
                    var index = layer.open({
                        title: '入库操作',
                        type: 2,
                        shade: 0.2,
                        maxmin: true,
                        shadeClose: true,
                        area: ['100%', '100%'],
                        content: '/put_storage_manage_add',
                    });
                    $(window).on("resize", function () {
                        layer.full(index);
                    });
                }
            })
            //监听表格复选框选择
            table.on('checkbox(currentTableFilter)', function (obj) {
                console.log(obj)
            });

            table.on('tool(currentTableFilter)', function (obj) {
                var data = obj.data;
                if (obj.event === 'edit') {
                    var index = layer.open({
                        title: '编辑装备器材',
                        type: 2,
                        shade: 0.2,
                        maxmin: true,
                        shadeClose: true,
                        area: ['100%', '100%'],
                        content: '/product_manage_edit',
                        success: function (layero, index) {
                            let iframe = window['layui-layer-iframe' + index];
                            iframe.parent_to_child(obj);
                        }
                    });
                    $(window).on("resize", function () {
                    });
                    return false;
                } else if (obj.event === 'delete') {
                    layer.confirm('真的删除行么?', {icon: 3, title: '确认删除'}, function (index) {
                        obj.del();
                        layer.close(index);
                        $.ajax({
                            url: '/product_manage_del',
                            type: "POST",
                            dataType: "JSON",
                            data: {'id': obj.data.id, 'batch': '0'},
                            traditional: true,
                            success: function (result) {
                                if (result.success) {
                                    layer.msg(result.msg, {icon: 1});
                                } else {
                                    layer.msg(result.msg, {icon: 2});
                                }
                            },
                            error: function (result) {
                                alert("接口错误！！");
                            }
                        });
                        return false;
                    });
                }
            });


            table.on('edit(currentTableFilter)', function (obj) { //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
                // console.log(obj.value); //得到修改后的值
                // console.log(obj.field); //当前编辑的字段名
                console.log(obj.data); //所在行的所有相关数据
                //传给后台
                var URL = '/role/' + obj.data.id + '/';
                $.ajax({
                    url: URL,
                    type: "put",
                    data: obj.data,
                    success: function (result) {
                        if (result.success) {
                            layer.msg(result.msg, {icon: 1});
                        } else {
                            layer.msg(result.msg, {icon: 2});
                        }

                    },
                    error: function (result) {
                        alert("接口错误！！");
                    }
                });
                return false;


            });

            // 监听开关
            form.on('switch(role-enable)', function (obj) {
                // console.log(obj.elem.attributes['roleID'].nodeValue);
                // console.log(obj);
                let roleId = obj.elem.attributes['roleID'].nodeValue;

                let operate
                if (obj.elem.checked) {
                    operate = 'enable'
                } else {
                    operate = 'disable'
                }
                let loading = layer.load()

                $.ajax({
                    url: "/role/enable/",
                    type: "put",
                    data: {
                        id: roleId,
                        enable: operate
                    },
                    success: function (result) {
                        layer.close(loading)
                        if (result.success) {
                            layer.msg(result.msg, {icon: 1});
                        } else {
                            layer.msg(result.msg, {icon: 2});
                        }
                    },
                    error: function (result) {
                        alert("接口错误！！");
                    }
                });
                return false;

            })

            // window.refresh = function (param) {
            //   table.reload('currentTableId', { where: params })
            // }

            //监听扫码
            $('#product-id-input').keypress(function (event) {
                if (event.key === "Enter" || event.keyCode === 13) { // 检测回车键
                    event.preventDefault(); // 阻止表单默认提交行为
                    var productId = $(this).val(); // 获取输入的装备器材 ID

                    // 发送 AJAX 请求到后端减少装备器材数量
                    $.ajax({
                        url: '/put_storage_manage_list/',
                        type: 'POST',
                        data: {
                            'fk_product': productId,
                            'quantity': 1,
                            'fk_department': {{ request.session.dept_id }}
                        },
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader('X-CSRFTOKEN', token); // 设置 CSRF Token
                        },
                        success: function (response) {
                            console.log(response)
                            if (response.success) {
                                $('#product-id-input').val('');
                                layer.msg('装备器材数量增加成功', {icon: 1});
                                // 刷新表格
                                table.reload('currentTableId');
                            } else {
                                layer.alert(response.msg);
                            }
                        },
                        error: function (xhr, status, error) {
                            layer.msg('请求失败，请稍后重试', {icon: 2});
                        }
                    });
                }
            });

        }
    );
</script>

</body>
</html>